export type FileRules = {
  // 最大字节数（例如 10MB = 10 * 1024 * 1024）
  maxBytes?: number
  // 允许的 MIME 类型（如 ["application/pdf", "image/png"]）
  allowedMimeTypes?: string[]
  // 允许的扩展名（不含点，如 ["pdf", "png"]，大小写不敏感）
  allowedExtensions?: string[]
}

export function getFileExtension(name: string): string | null {
  const idx = name.lastIndexOf('.')
  if (idx === -1) return null
  return name.slice(idx + 1).toLowerCase()
}

export function validateFile(file: File, rules?: FileRules): { ok: boolean; reason?: string } {
  if (!rules) return { ok: true }
  const { maxBytes, allowedMimeTypes, allowedExtensions } = rules

  if (typeof maxBytes === 'number' && maxBytes > 0) {
    if (file.size > maxBytes) {
      return { ok: false, reason: `文件过大，上限 ${(maxBytes / (1024 * 1024)).toFixed(1)}MB` }
    }
  }

  if (Array.isArray(allowedMimeTypes) && allowedMimeTypes.length > 0) {
    const type = (file.type || '').toLowerCase()
    if (type && !allowedMimeTypes.map(t => t.toLowerCase()).includes(type)) {
      return { ok: false, reason: `文件类型不被允许：${file.type}` }
    }
  }

  if (Array.isArray(allowedExtensions) && allowedExtensions.length > 0) {
    const ext = getFileExtension(file.name)
    if (!ext || !allowedExtensions.map(e => e.toLowerCase()).includes(ext)) {
      return { ok: false, reason: `文件扩展名不被允许：.${ext || '未知'}` }
    }
  }

  return { ok: true }
}

export function enforceFileValidation(file: File, rules?: FileRules) {
  const { ok, reason } = validateFile(file, rules)
  if (!ok) throw new Error(reason || '文件不符合上传要求')
}

// 下载前对后端返回的 meta 做校验
export function validateDownloadMeta(meta: { totalSize: number | null; contentType?: string }, rules?: FileRules)
  : { ok: boolean; reason?: string } {
  if (!rules) return { ok: true }
  const { maxBytes, allowedMimeTypes } = rules

  if (typeof maxBytes === 'number' && maxBytes > 0) {
    if (meta.totalSize != null && meta.totalSize > maxBytes) {
      return { ok: false, reason: `文件过大（${(meta.totalSize / (1024 * 1024)).toFixed(1)}MB），上限 ${(maxBytes / (1024 * 1024)).toFixed(1)}MB` }
    }
  }

  if (Array.isArray(allowedMimeTypes) && allowedMimeTypes.length > 0) {
    const type = (meta.contentType || '').toLowerCase()
    if (type && !allowedMimeTypes.map(t => t.toLowerCase()).includes(type)) {
      return { ok: false, reason: `文件类型不被允许：${meta.contentType}` }
    }
  }

  return { ok: true }
}

export function enforceDownloadMeta(meta: { totalSize: number | null; contentType?: string }, rules?: FileRules) {
  const { ok, reason } = validateDownloadMeta(meta, rules)
  if (!ok) throw new Error(reason || '文件不符合下载要求')
}
